const express = require('express')
const cors = require('cors')
const helmet = require('helmet')
const morgan = require('morgan')
const { createServer } = require('http')
const { Server } = require('socket.io')
const sequelize = require('./config/database')

// 路由导入
const authRoutes = require('./routes/auth')
const erpRoutes = require('./routes/erp')
const mesRoutes = require('./routes/mes')
const productionRoutes = require('./routes/production')
const realtimeRoutes = require('./routes/realtime')

const app = express()
const server = createServer(app)
const io = new Server(server, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"]
  }
})

// 中间件
app.use(helmet())
app.use(cors())
app.use(morgan('combined'))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// 路由
app.use('/api/auth', authRoutes)
app.use('/api/erp', erpRoutes)
app.use('/api/mes', mesRoutes)
app.use('/api/production', productionRoutes)
app.use('/api/realtime', realtimeRoutes)

// Socket.IO 实时通信
io.on('connection', (socket) => {
  console.log('客户端已连接:', socket.id)
  
  socket.on('join_room', (room) => {
    socket.join(room)
    console.log(`客户端 ${socket.id} 加入房间: ${room}`)
  })
  
  socket.on('disconnect', () => {
    console.log('客户端已断开连接:', socket.id)
  })
})

// 全局错误处理
app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).json({ message: '服务器内部错误' })
})

// 404处理
app.use((req, res) => {
  res.status(404).json({ message: '接口不存在' })
})

// 数据库连接
const PORT = process.env.PORT || 5000

async function startServer() {
  try {
    await sequelize.authenticate()
    console.log('数据库连接成功')
    
    await sequelize.sync({ alter: true })
    console.log('数据库同步完成')
    
    server.listen(PORT, () => {
      console.log(`服务器运行在端口 ${PORT}`)
    })
  } catch (error) {
    console.error('启动失败:', error)
  }
}

startServer()

module.exports = { app, io }
